package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.ruoyi.business.PortServerIce.TradeServantPrx;
import com.ruoyi.business.constant.TradeConstants;
import com.ruoyi.business.domain.BusinessManualConfig;
import com.ruoyi.business.domain.BusinessManualRecord;
import com.ruoyi.business.dto.PSIceOrder;
import com.ruoyi.business.dto.TicketDTO;
import com.ruoyi.business.enumType.PSIceMarket;
import com.ruoyi.business.enumType.PSIceOrderState;
import com.ruoyi.business.enumType.PSIceOrderType;
import com.ruoyi.business.exception.TradeException;
import com.ruoyi.business.holder.PSIceErrorCodeHolder;
import com.ruoyi.business.holder.PSIceOrderOutHolder;
import com.ruoyi.business.mapper.BusinessManualConfigMapper;
import com.ruoyi.business.mapper.BusinessManualRecordMapper;
import com.ruoyi.business.service.IBusinessManualRecordService;
import com.ruoyi.business.service.IBusinessTradeRecordService;
import com.ruoyi.business.util.PythonUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 手工策略配置Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-14
 */
@Service
public class BusinessManualRecordServiceImpl implements IBusinessManualRecordService
{
    @Autowired
    private BusinessManualRecordMapper businessManualRecordMapper;

    @Autowired
    private BusinessManualConfigMapper businessManualConfigMapper;

    @Autowired
    private TradeServantPrx tradeServantPrx;


    @Value("${trade.rate}")
    private String tradeRate;

    private static final Logger logger = LoggerFactory.getLogger(BusinessManualRecordServiceImpl.class);


    /**
     * 查询手工策略配置
     * 
     * @param id 手工策略配置主键
     * @return 手工策略配置
     */
    @Override
    public BusinessManualRecord selectBusinessManualRecordById(Long id)
    {
        return businessManualRecordMapper.selectBusinessManualRecordById(id);
    }

    /**
     * 查询手工策略配置列表
     * 
     * @param businessManualRecord 手工策略配置
     * @return 手工策略配置
     */
    @Override
    public List<BusinessManualRecord> selectBusinessManualRecordList(BusinessManualRecord businessManualRecord)
    {
        return businessManualRecordMapper.selectBusinessManualRecordList(businessManualRecord);
    }

    /**
     * 新增手工策略配置
     * 
     * @param businessManualRecord 手工策略配置
     * @return 结果
     */
    @Override
    public int insertBusinessManualRecord(BusinessManualRecord businessManualRecord)
    {
        BusinessManualConfig businessManualConfig = businessManualConfigMapper.selectBusinessManualConfigById(businessManualRecord.getStrategyId());
        if(Objects.isNull(businessManualConfig)){
            throw new TradeException("查询手工开仓交易策略为空");
        }
        // 获取最新价格
        TicketDTO symbolCurrData = PythonUtil.getSymbolCurrData(businessManualConfig.getStockCode());
        if(Objects.isNull(symbolCurrData)){
            logger.error("获取标的："+businessManualConfig.getStockCode()+",最新价格数据为空");
            throw new TradeException(businessManualConfig.getStockCode()+" 获取最新价格为空");
        }
        BigDecimal price = BigDecimal.valueOf(symbolCurrData.getPrice());
        int delegateVolume = businessManualRecord.getDelegateAmount().divide(price,0).divide(new BigDecimal("100"),0).multiply(new BigDecimal("100")).intValue();

        // 盘口价下浮1% 卖出 上浮1% 买入
        BigDecimal tradePrice = BigDecimal.ZERO;
        if (PSIceOrderType.Buy.equals(PSIceOrderType.valueOf(businessManualRecord.getDelegateType()))) {
            tradePrice = price.multiply(new BigDecimal(tradeRate).multiply(new BigDecimal("0.01")).add(BigDecimal.ONE));
        } else if (PSIceOrderType.Sell.equals(PSIceOrderType.valueOf(businessManualRecord.getDelegateType()))) {
            tradePrice = price.multiply(BigDecimal.ONE.subtract(new BigDecimal(tradeRate).multiply(new BigDecimal("0.01"))));
        }
        String stockCode = businessManualConfig.getStockCode();
        List<String> stockSplitList = Arrays.asList(stockCode.split("\\."));

        String stockPrefix = stockSplitList.get(0);
        PSIceMarket sh = PSIceMarket.SH;
        if (TradeConstants.SYMBOL_PREFIX_SHSE.equals(stockPrefix)) {
            sh = PSIceMarket.SH;
        } else if (TradeConstants.SYMBOL_PREFIX_SZSE.equals(stockPrefix)) {
            sh = PSIceMarket.SZ;
        } else {
            logger.error("交易标的只能是沪市或者深市股票");
        }
        stockCode = stockSplitList.get(1);
        PSIceOrder psIceOrder = new PSIceOrder(0, null, sh, PSIceOrderType.valueOf(businessManualRecord.getDelegateType()), stockCode, (long) (tradePrice.doubleValue() * 10000),delegateVolume, null);
        PSIceOrderOutHolder psIceOrderOutHolder = new PSIceOrderOutHolder();
        PSIceErrorCodeHolder psIceErrorCodeHolder = new PSIceErrorCodeHolder();
        int i = tradeServantPrx.SendOrder(null, psIceOrder, psIceOrderOutHolder, psIceErrorCodeHolder);
        System.out.println("Received result from server: " + i);
        businessManualRecord.setStockCode(businessManualConfig.getStockCode());
        businessManualRecord.setPrice(tradePrice);
        businessManualRecord.setOrderNo(psIceOrderOutHolder.value.OrderNo);
        businessManualRecord.setCreateTime(new Date());
        businessManualRecord.setDelegateAmount(businessManualRecord.getDelegateAmount());
        businessManualRecord.setDelegateVolume(delegateVolume);
        businessManualRecord.setDelegateType(businessManualRecord.getDelegateType());
        businessManualRecord.setDelegateState(PSIceOrderState.Undeclared.value());
        businessManualRecord.setExchange(sh.value());
        businessManualRecord.setDelegateCancle(false);
        // 执行成功
        if (i == 0) {
            businessManualRecord.setTradingStatus(true);
            return  businessManualRecordMapper.insertBusinessManualRecord(businessManualRecord);
        } else {
            businessManualRecord.setTradingStatus(false);
            businessManualRecord.setErrorMsg(psIceErrorCodeHolder.value.Message);
            return businessManualRecordMapper.insertBusinessManualRecord(businessManualRecord);
        }

    }

    /**
     * 修改手工策略配置
     * 
     * @param businessManualRecord 手工策略配置
     * @return 结果
     */
    @Override
    public int updateBusinessManualRecord(BusinessManualRecord businessManualRecord)
    {
        return businessManualRecordMapper.updateBusinessManualRecord(businessManualRecord);
    }

    /**
     * 批量删除手工策略配置
     * 
     * @param ids 需要删除的手工策略配置主键
     * @return 结果
     */
    @Override
    public int deleteBusinessManualRecordByIds(Long[] ids)
    {
        return businessManualRecordMapper.deleteBusinessManualRecordByIds(ids);
    }

    /**
     * 删除手工策略配置信息
     * 
     * @param id 手工策略配置主键
     * @return 结果
     */
    @Override
    public int deleteBusinessManualRecordById(Long id)
    {
        return businessManualRecordMapper.deleteBusinessManualRecordById(id);
    }
}
